package com.hellobike.haxing.modules.wms.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.hellobike.haxing.common.system.vo.LoginUser;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.common.system.query.QueryGenerator;
import com.hellobike.haxing.modules.wms.dto.ExportPutawayDto;
import com.hellobike.haxing.modules.wms.dto.StockTaskDto;
import com.hellobike.haxing.modules.wms.entity.DocPutaway;
import com.hellobike.haxing.modules.wms.entity.Location;
import com.hellobike.haxing.modules.wms.exception.WmsExportException;
import com.hellobike.haxing.modules.wms.exception.WmsServiceException;
import com.hellobike.haxing.modules.wms.facade.WmsExportFacade;
import com.hellobike.haxing.modules.wms.facade.WmsReceiveFacade;
import com.hellobike.haxing.modules.wms.service.IDocPutawayService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellobike.haxing.modules.wms.service.ILocationService;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import com.hellobike.haxing.common.annotation.AutoLog;

/**
* @Description: t_wms_doc_putaway
* @Author: haxing-boot
* @Date:   2020-01-09
* @Version: V1.0
*/
@RestController
@RequestMapping("/wms/docPutaway")
@Slf4j
public class DocPutawayController extends WmsBaseController<DocPutaway, IDocPutawayService> {
   @Autowired
   private IDocPutawayService docPutawayService;
    @Autowired
    private WmsReceiveFacade wmsReceiveFacade;
    @Autowired
    private ILocationService locationService;

   /**
    * 分页列表查询
    *
    * @param docPutaway
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   @AutoLog(value = "t_wms_doc_putaway-分页列表查询")
   @GetMapping(value = "/list")
   public Result<?> queryPageList(DocPutaway docPutaway,
                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                  HttpServletRequest req) {
       docPutaway.setWarehouseId(getWarehouseId());
       QueryWrapper<DocPutaway> queryWrapper = QueryGenerator.initQueryWrapper(docPutaway, req.getParameterMap());
       Page<DocPutaway> page = new Page<DocPutaway>(pageNo, pageSize);
       page.addOrder(OrderItem.desc("id"));
       IPage<DocPutaway> pageList = docPutawayService.page(page, queryWrapper);
       return Result.ok(pageList);
   }

   /**
    *   添加
    *
    * @param docPutaway
    * @return
    */
   @AutoLog(value = "t_wms_doc_putaway-添加",operateType=2)
   @PostMapping(value = "/add")
   public Result<?> add(@RequestBody DocPutaway docPutaway) {
       docPutawayService.save(docPutaway);
       return Result.ok("添加成功！");
   }

   /**
    *  编辑
    *
    * @param docPutaway
    * @return
    */
   @AutoLog(value = "t_wms_doc_putaway-编辑",operateType=3)
   @PutMapping(value = "/edit")
   public Result<?> edit(@RequestBody DocPutaway docPutaway) {
       docPutawayService.updateById(docPutaway);
       return Result.ok("编辑成功!");
   }

   /**
    *   通过id删除
    *
    * @param id
    * @return
    */
   @AutoLog(value = "t_wms_doc_putaway-删除",operateType=4)
   @DeleteMapping(value = "/delete")
   public Result<?> delete(@RequestParam(name="id",required=true) String id) {
       docPutawayService.removeById(id);
       return Result.ok("删除成功!");
   }

   /**
    *  批量删除
    *
    * @param ids
    * @return
    */
   @AutoLog(value = "t_wms_doc_putaway-批量删除",operateType=4)
   @DeleteMapping(value = "/deleteBatch")
   public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       this.docPutawayService.removeByIds(Arrays.asList(ids.split(",")));
       return Result.ok("批量删除成功!");
   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   @GetMapping(value = "/queryById")
   public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
       DocPutaway docPutaway = docPutawayService.getById(id);
       if(docPutaway==null) {
           return Result.error("未找到对应数据");
       }
       return Result.ok(docPutaway);
   }

    /**
     * 导出excel
     */
    @AutoLog(value = "t_wms_doc_putaway-导出excel",operateType=6)
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(@RequestParam Long id) throws WmsExportException {
        try {
            DocPutaway docPutaway = docPutawayService.getById(id);
            String title = "上架-"+docPutaway.getOrderCode();
            List<ExportPutawayDto> exportList = wmsExportFacade.exportPutaway(id);
            return export(title,ExportPutawayDto.class,exportList);
        } catch (Exception e) {
            throw new WmsExportException(e);
        }
    }
   /**
     * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
   @AutoLog(value = "t_wms_doc_putaway-导入excel",operateType=5)
   @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
   public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
       return super.importExcel(request, response, DocPutaway.class);
   }

    @AutoLog(value = "t_wms_doc_putaway-上架单任务查询")
    @GetMapping(value = "/stockTaskList")
   public Result<?> getStockTaskListByPutawayId(@RequestParam Long putawayId){
        List<StockTaskDto> taskDtoList = null;
        try {
            taskDtoList = wmsReceiveFacade.queryTaskInfoByPutawayId(putawayId);
        } catch (WmsServiceException e) {
            return Result.error("服务异常"+e.getMessage());
        }
        return Result.ok(taskDtoList);
   }

   /*
{"note":"1234567",
"skus":[{"id":6,"taskNo":"TK1202001111732458501215929531528785921","taskType":"PA","taskStatus":"PUBLISHED",
"skuId":3,"qty":66,"batchId":1,"docOperId":2,"docOperNo":"PA11215949878558867458","docId":11,"docLineId":6,
"docNo":"ASN11215889695036116994","docType":"ASN","lineStatus":"COMPLETED","fmLocId":1,"planLocId":2,"warehouseId":1,
"damaged":0,"fmStockId":1,"createTime":"2020-01-11 17:32:45","updateTime":"2020-01-11 18:53:37","createBy":1,"updateBy":1,"deleted":0,
"fmLocCode":"ZC_01_01_01","planLocCode":"SH_01_01_01","toLocCode":"1213213","spuName":"测试SPU",
"spuCode":"100100100001","skuCode":"1001","barCode":"2001"},
{"id":5,"taskNo":"TK1202001111730149591215928898646061058","taskType":"PA","taskStatus":"PUBLISHED","skuId":3,"qty":1234,"batchId":1,"docOperId":2,"docOperNo":"PA11215949878558867458","docId":12,"docLineId":7,"docNo":"ASN11215921517321203714","docType":"ASN","lineStatus":"COMPLETED","fmLocId":1,"planLocId":2,"warehouseId":1,"damaged":0,"fmStockId":1,"createTime":"2020-01-11 17:30:15","updateTime":"2020-01-11 18:53:37","createBy":1,"updateBy":1,"deleted":0,"fmLocCode":"ZC_01_01_01","planLocCode":"SH_01_01_01","toLocCode":"123123213213","spuName":"测试SPU","spuCode":"100100100001","skuCode":"1001","barCode":"2001"}]
,"putawayId":2}

    */
    @AutoLog(value = "t_wms_doc_putaway-确认上架",operateType=5)
    @RequestMapping(value = "/confirmPutaway", method = RequestMethod.POST)
   public Result<?> confirmPutaway(@RequestBody JSONObject json){
        log.info(json.toJSONString());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Integer userId = sysUser.getId();
        Long warehouseId = getWarehouseId();
        log.info("======================>sysUser;"+sysUser);
        log.info("======================>warehouseId;"+warehouseId);
        String note = json.getString("note");
        String opName = json.getString("opName");
        Long putawayId = json.getLong("putawayId");
        JSONArray skus = json.getJSONArray("skus");
        List<StockTaskDto> taskList = new ArrayList<>();
        try {
            for (int i = 0; i < skus.size(); i++) {
                JSONObject skusJSONObject = skus.getJSONObject(i);
                StockTaskDto task = new StockTaskDto();
                task.setId(skusJSONObject.getLong("id"));
                task.setReasonDesc(skusJSONObject.getString("reasonDesc"));
                task.setSkuProductionDate(skusJSONObject.getDate("skuProductionDate"));
                String toLocCode = skusJSONObject.getString("toLocCode");
                if(StringUtils.isEmpty(toLocCode)){
                    throw new WmsServiceException("上架库位必须填写");
                }
                Location location = locationService.getByLocCodeAndWarehouseId(toLocCode,warehouseId);
                if(null == location){
                    throw new WmsServiceException("库位不存在"+toLocCode);
                }
                BigDecimal actQty = skusJSONObject.getBigDecimal("actQty");
                if(null == actQty || actQty.compareTo(BigDecimal.ZERO)<0){
                    throw new WmsServiceException("上架数量不合法"+actQty);
                }
                task.setActQty(actQty);
                task.setToLocId(location.getId());
                taskList.add(task);
            }
            wmsReceiveFacade.confirmPutaway(taskList,putawayId,opName,note,warehouseId,userId);
        } catch (Exception e) {
            return Result.error("服务异常:"+e.getMessage());
        }
        return Result.ok();
   }

}
